import { Cls } from "../util/Defined";
import { EventMgr } from "../event/EventMgr";
import { Bits } from "../util/Bits";
import { TypeUtil } from "../util/TypeUtil";
import { ECSCmp } from "./ECSCmp";
import { ECSCmpMgr } from "./ECSCmpMgr";
import { ECSEntity } from "./ECSEntity";

/** [ECS]过滤器参数 */
export interface IECSFilter {
    /** 包含组件(有其一则匹配) */
    includeOne?: Cls<ECSCmp>[]
    /** 包含组件(都有才匹配) */
    includeAll?: Cls<ECSCmp>[]
    /** 排除组件(有其一则排除) */
    excludeOne?: Cls<ECSCmp>[]
    /** 排除组件(都有才排除) */
    excludeAll?: Cls<ECSCmp>[]
}

/** [ECS]过滤器事件 */
export const enum ECSFilterEvent {
    entityAdd = "entityAdd",
    entityRemove = "entityRemove",
    cmpAdd = "cmpAdd",
    cmpRemove = "cmpRemove",
}

/** [ECS]过滤器事件携带参数 */
export interface ECSFilterEventData {
    [ECSFilterEvent.entityAdd]: ECSEntity,
    [ECSFilterEvent.entityRemove]: ECSEntity,
    [ECSFilterEvent.cmpAdd]: ECSCmp,
    [ECSFilterEvent.cmpRemove]: ECSCmp,
}

/**
 * [ECS]过滤器
 */
export class ECSFilter extends EventMgr<ECSFilterEventData> {

    /** 引用计数 用来做移除时是否销毁的判断 */
    ref = 1;
    /** 匹配到的实体的所有组件 */
    readonly entityCmpsMap = new Map<ECSEntity, Set<ECSCmp>>();
    /** 匹配到的所有组件 */
    readonly cmpsMap = new Map<Cls<ECSCmp>, Set<ECSCmp>>();
    /** 过滤器关注的组件 */
    readonly watchCmpTypes = new Set<Cls<ECSCmp>>();
    /** 发生变化的实体 */
    protected _dirtyEntities = new Set<ECSEntity>();
    /** 等待添加的组件 */
    protected _waitAddCmpsMap = new Map<Cls<ECSCmp>, Set<ECSCmp>>();
    /** 等待移除的组件 */
    protected _waitRemoveCmpsMap = new Map<Cls<ECSCmp>, Set<ECSCmp>>();
    /** 有需要添加的组件 */
    protected _cmpAddDirty = false;
    /** 有需要移除的组件 */
    protected _cmpRemoveDirty = false;

    protected _includeOneBits: Bits;
    protected _includeAllBits: Bits;
    protected _excludeOneBits: Bits;
    protected _excludeAllBits: Bits;

    constructor(
        /** 过滤器key值 相同include和exclude的key值唯一 */
        readonly key: string,
        /** 过滤器参数 */
        readonly ifilter: Readonly<IECSFilter>
    ) {
        super();
        if (ifilter.includeOne?.length > 0) {
            this._includeOneBits = new Bits();
            ifilter.includeOne.forEach(cmpType => {
                this._includeOneBits.setBit(ECSCmpMgr.getCmpIdx(cmpType), 1);
                this.cmpsMap.set(cmpType, new Set());
                this.watchCmpTypes.add(cmpType);
                this._waitAddCmpsMap.set(cmpType, new Set());
                this._waitRemoveCmpsMap.set(cmpType, new Set());
            });
        }
        if (ifilter.includeAll?.length > 0) {
            this._includeAllBits = new Bits();
            ifilter.includeAll.forEach(cmpType => {
                this._includeAllBits.setBit(ECSCmpMgr.getCmpIdx(cmpType), 1);
                this.cmpsMap.set(cmpType, new Set());
                this.watchCmpTypes.add(cmpType);
                this._waitAddCmpsMap.set(cmpType, new Set());
                this._waitRemoveCmpsMap.set(cmpType, new Set());
            });
        }
        if (ifilter.excludeOne?.length > 0) {
            this._excludeOneBits = new Bits();
            ifilter.excludeOne.forEach(cmpType => {
                this._excludeOneBits.setBit(ECSCmpMgr.getCmpIdx(cmpType), 1);
                this.watchCmpTypes.add(cmpType);
            });
        }
        if (ifilter.excludeAll?.length > 0) {
            this._excludeAllBits = new Bits();
            ifilter.excludeAll.forEach(cmpType => {
                this._excludeAllBits.setBit(ECSCmpMgr.getCmpIdx(cmpType), 1);
                this.watchCmpTypes.add(cmpType);
            });
        }
    }

    /**
     * 实体发生变化
     * @param entity 实体
     */
    onEntityChange(entity: ECSEntity) {
        this._dirtyEntities.add(entity);
    }

    /**
     * 实体被移除
     * @param entity 实体
     */
    onEntityRemove(entity: ECSEntity) {
        if (this.entityCmpsMap.has(entity)) {
            this._dirtyEntities.add(entity);
        }
    }

    /**
     * 组件添加
     * @param cmp 组件
     */
    onCmpAdd(cmp: ECSCmp) {
        const cmpType = TypeUtil.getCls(cmp);
        if (this.cmpsMap.has(cmpType)) {
            //是包含组件
            if (this.entityCmpsMap.has(cmp.entity)) {
                this._cmpAddDirty = true;
                this._waitAddCmpsMap.get(cmpType).add(cmp);
            } else {
                //已经匹配成功的再添加包含组件也不会改变结果
                //所以判断下没有匹配成功的才通知实体改变
                this.onEntityChange(cmp.entity);
            }
        } else {
            //是排除组件
            if (this.entityCmpsMap.has(cmp.entity)) {
                //没有匹配成功的再添加排除组件也不会改变结果
                //所以判断下已经匹配成功的才通知实体改变
                this.onEntityChange(cmp.entity);
            }
        }
    }

    /**
     * 组件移除
     * @param cmp 组件
     */
    onCmpRemove(cmp: ECSCmp) {
        const cmpType = TypeUtil.getCls(cmp);
        if (this.cmpsMap.has(cmpType)) {
            //是包含组件
            if (this.entityCmpsMap.has(cmp.entity)) {
                this._cmpRemoveDirty = true;
                this._waitRemoveCmpsMap.get(cmpType).add(cmp);
                //没有匹配成功的再移除包含组件也不会改变结果
                //所以判断下已经匹配成功的才通知实体改变
                this.onEntityChange(cmp.entity);
            }
        } else {
            //是排除组件
            if (!this.entityCmpsMap.has(cmp.entity)) {
                //已经匹配成功的再移除排除组件也不会改变结果
                //所以判断下还没有匹配成功的才通知实体改变
                this.onEntityChange(cmp.entity);
            }
        }
    }

    protected addEntity(entity: ECSEntity) {
        const entityCmps = new Set<ECSCmp>();
        this.entityCmpsMap.set(entity, entityCmps);
        this.cmpsMap.forEach((cmps, cmpType) => {
            //将所有需要包含的组件添加进来
            entity.getCmps(cmpType).forEach(cmp => {
                entityCmps.add(cmp);
                cmps.add(cmp);
                this.send(ECSFilterEvent.cmpAdd, cmp);
            });
        });
        this.send(ECSFilterEvent.entityAdd, entity);
    }

    protected removeEntity(entity: ECSEntity) {
        const entityCmps = this.entityCmpsMap.get(entity);
        this.entityCmpsMap.delete(entity);
        this.cmpsMap.forEach(cmps => {
            //移除所有实体相关组件
            entityCmps.forEach(cmp => {
                cmps.delete(cmp);
                this.send(ECSFilterEvent.cmpRemove, cmp);
            });
        });
        this.send(ECSFilterEvent.entityRemove, entity);
    }

    /**
     * 更新有组件变化的实体
     * 检查实体当前的组件是否与筛选条件匹配
     */
    update() {
        if (this._dirtyEntities.size > 0) {
            this._dirtyEntities.forEach(e => {
                if (e.removed) {
                    if (this.entityCmpsMap.has(e)) {
                        this.removeEntity(e);
                    }
                } else {
                    if (this.checkMatch(e.cmpMgr.cmpBits)) {
                        if (!this.entityCmpsMap.has(e)) {
                            this.addEntity(e);
                        }
                    } else {
                        if (this.entityCmpsMap.has(e)) {
                            this.removeEntity(e);
                        }
                    }
                }
            });
            this._dirtyEntities.clear();
        }

        if (this._cmpAddDirty) {
            this._cmpAddDirty = false;

            this._waitAddCmpsMap.forEach((adds, cmpType) => {
                if (adds.size > 0) {
                    const cmps = this.cmpsMap.get(cmpType);
                    adds.forEach(cmp => {
                        const entityCmps = this.entityCmpsMap.get(cmp.entity);
                        if (entityCmps) {
                            entityCmps.add(cmp);
                            cmps.add(cmp);
                            this.send(ECSFilterEvent.cmpAdd, cmp);
                        }
                    });
                    adds.clear();
                }
            });
        }

        if (this._cmpRemoveDirty) {
            this._cmpRemoveDirty = false;
            this._waitRemoveCmpsMap.forEach((removes, cmpType) => {
                if (removes.size > 0) {
                    const cmps = this.cmpsMap.get(cmpType);
                    removes.forEach(cmp => {
                        const entityCmps = this.entityCmpsMap.get(cmp.entity);
                        entityCmps?.delete(cmp);
                        cmps.delete(cmp);
                        this.send(ECSFilterEvent.cmpRemove, cmp);
                    });
                    removes.clear();
                }
            });
        }

    }

    /**
     * 检查组件bits是否与当前筛选条件匹配
     * @param cmpBits 实体组件bits
     */
    checkMatch(cmpBits: Bits) {
        if (this._includeOneBits && !this._includeOneBits.checkHasOne(cmpBits)) {
            return false;
        }
        if (this._includeAllBits && !this._includeAllBits.checkHasAll(cmpBits)) {
            return false;
        }
        if (this._excludeOneBits && this._excludeOneBits.checkHasOne(cmpBits)) {
            return false;
        }
        if (this._excludeAllBits && this._excludeAllBits.checkHasAll(cmpBits)) {
            return false;
        }
        return true;
    }

    /**
     * 销毁过滤器
     */
    destroy() {
        this.offAll();
        this.entityCmpsMap.clear();
        this.watchCmpTypes.clear();
        this.cmpsMap.clear();
        this._dirtyEntities.clear();
        this._waitAddCmpsMap.clear();
        this._waitRemoveCmpsMap.clear();
    }

}